package com.nuanshui.heatedloan.baseservice.service;

import com.google.common.collect.Lists;
import com.nuanshui.framework.annotation.NeedLogin;
import com.nuanshui.framework.utils.redis.JedisUtil;
import com.nuanshui.heatedloan.baseservice.dal.mapper.FunctionInterfaceMapper;
import com.nuanshui.heatedloan.baseservice.facade.FunctionInterfaceService;
import com.nuanshui.heatedloan.baseservice.model.FunctionInterface;
import com.nuanshui.heatedloan.constant.CacheConstants;
import com.nuanshui.heatedloan.constant.ServiceConstant;
import com.nuanshui.heatedloan.constant.TransactionManagerType;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;


@Service(ServiceConstant.FUNCTIONINTERFACESERVICE)
@Transactional(readOnly=true,  value = TransactionManagerType.BASE_SERVICE_TRANSACTION_MANAGER)
public class FunctionInterfaceServiceImpl  extends CommonServiceImpl  implements FunctionInterfaceService,InitializingBean{

	@Autowired
	private FunctionInterfaceMapper functionInterfaceMapper;
	
	@Autowired
	private  JedisUtil jedisUtil;
	
	@Override
	@Transactional(readOnly=false,value=TransactionManagerType.BASE_SERVICE_TRANSACTION_MANAGER)
	public void saveNotExistBatch(List<FunctionInterface> functionInterfaces) {
			List<FunctionInterface> hasFunctionInterfaces = functionInterfaceMapper.findAll();
			List<FunctionInterface> saveArray = new ArrayList<FunctionInterface>();
			List<String> deleteIds = new ArrayList<String>();
			// 判断没有添加上的
			for (FunctionInterface fi : functionInterfaces) {
				if (!hasFunctionInterfaces.contains(fi)) {
					fi.setStatus(1);
					saveArray.add(fi);
				}
			}
			/**
			 * 判断删除的
			 */
			for (FunctionInterface dictionary : hasFunctionInterfaces) {
				if (!functionInterfaces.contains(dictionary)) {
				     deleteIds.add(dictionary.getId());
				}

			}
			if(deleteIds.size()>0) {
				functionInterfaceMapper.deleteBatch(deleteIds);
			}
			if(saveArray.size()>0) {
				functionInterfaceMapper.saveBatch(saveArray);		

			}
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		try {
			saveNotExistBatch(get("com.nuanshui.restapi"));
			saveFunctionInterfaceToCache();
		} catch (Exception e) {
		}
		
		
	}
	
	/**
	 * 初始化系统的角色所访问的功能信息
	 * 
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public  List<FunctionInterface> get(final String pname) {
		jedisUtil.del(CacheConstants.NEED_LOGIN_URL_LIST);
		
		try {
			List<FunctionInterface> datas = new ArrayList<FunctionInterface>();
			List<String> ps = getClassByPackage(pname);
			for (String p : ps) {
				String pc =  p.substring(p.indexOf(pname),p.lastIndexOf(".class"));
				// 得到了类的class对象
				Class clz = Class.forName(pc);
				if (clz.isAnnotationPresent(Controller.class) || clz.isAnnotationPresent(RestController.class)) {
					Method Methods[] = clz.getMethods();
					//String key = clz.getSimpleName();
					String parentPath = "";
					if(clz.isAnnotationPresent(RequestMapping.class)) {
						RequestMapping requestMapping = (RequestMapping) clz.getAnnotation(RequestMapping.class);
						parentPath = requestMapping.value()[0];
					    
					}
					for (Method method : Methods) {
						if(method.isAnnotationPresent(RequestMapping.class)) {
							RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
							String urls[] = requestMapping.value();
							FunctionInterface functionInterface = new FunctionInterface();
							for(String  url :urls){
								if(url.startsWith("/") || parentPath.endsWith("/") ) {
									url  = parentPath+url;
									url.replace("//", "/");
								}else  {
									
									url  = parentPath+"/"+url;
								}
								functionInterface.setUrl(url);
								datas.add(functionInterface);
						 		if(method.isAnnotationPresent(NeedLogin.class)){
						 			jedisUtil.hset(CacheConstants.NEED_LOGIN_URL_LIST,url,"1");
								}
							}
							
							
						}
						
						
						
					}
				}
				
			}
			return datas;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 根据包获取所有的类
	 * 
	 * @param pname
	 * @return
	 */
	private static List<String>getClassByPackage(final String pname) {
		
		String pr = pname.replace(".", "/");
		URL url = FunctionInterfaceServiceImpl.class.getClassLoader().getResource(pr);
		if(url == null) return Lists.newArrayList();
		if(StringUtils.isEmpty(url.getPath())) return Lists.newArrayList();
		File file = new File(url.getPath());
		return getClass(file);
	}
	
	private  static List<String> getClass(File file) {
		List<String> classs = new ArrayList<String>();
		if(file.isDirectory()) {
			File files[] = file.listFiles();
			for(File f :files){
			 classs.addAll(getClass(f)); 
			}
		}else {
			String  name = file.getName();
			
			if (name.endsWith(".class")) {
				classs.add(file.getPath().replace("/",".").replace("\\", "."));
			}
		}
		return classs;
	}

	@Override
	public void saveFunctionInterfaceToCache() {
		jedisUtil.del(CacheConstants.URL_LIST);
		List<FunctionInterface> functionInterfaces = functionInterfaceMapper.findAll();
		
		for(FunctionInterface  functionInterface :functionInterfaces) {
			jedisUtil.hset(CacheConstants.URL_LIST,functionInterface.getUrl(),functionInterface.getStatus());
		}
		
	}
	@Override
	public Integer findAccessNum(String url) {
		return functionInterfaceMapper.findAccessNum(url);
	}

	@Override
	public FunctionInterface loadByUrl(String url) {
		return functionInterfaceMapper.loadByUrl(url);
	}
	
}
